package 复制文件的异常处理;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFileDemo {
    public static void main(String[] args) {

    }
    //抛出处理
    private static void method1()throws IOException {
        FileReader fr=new FileReader("fr.txt");
        FileWriter fw=new FileWriter("fw.txt");

        char[]chs= new char [1024];
        int len;
        while ((len=fr.read(chs))!=-1){
            fw.write(chs,0,len);
        }
        fr.close();
        fw.close();
    }

  /*  //JDK9的改进方案
    private static void method4()throws IOException{
        FileReader fr=new FileReader("fr.txt");
        FileWriter fw=new FileWriter("fw.txt");
        try(fr;fw) {
            char[] chs = new char[1024];
            int len;
            while ((len = fr.read(chs)) != -1) {
                fw.write(chs, 0, len);
            }
        }
//        fr.close();
//        fw.close();
    }*/


    //JDK7的改进方案 (自动释放资源）
    private static void method3() {
        try (FileReader fr = new FileReader("fr.txt");
             FileWriter fw = new FileWriter("fw.txt");){

            char[] chs = new char[1024];
            int len;
            while ((len = fr.read(chs)) != -1) {
                fw.write(chs, 0, len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
//        fr.close();
//        fw.close();
    }

    //try...catch...finally
    private static void method2() {
        FileReader fr=null;
        FileWriter fw=null;
        try{
        fr=new FileReader("fr.txt");
        fw=new FileWriter("fw.txt");

        char[]chs= new char [1024];
        int len;
        while ((len=fr.read(chs))!=-1){
            fw.write(chs,0,len);
        }
        fr.close();
        fw.close();
    }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fw!=null){
                try {
                    fr.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (fr!=null){
                try {
                    fw.close();
                    }catch (IOException e){
                    e.printStackTrace();
                }
            }
//            fr.close();
//            fw.close();
        }
        }
}
